<template>
  <div>
    <Page auto-content-height>
      <!-- 搜索条件 -->

      <!-- 表格 -->
      <FosoTable
        ref="DepartmentTable"
        :columns="tableColumns"
        :request-api="getDepListData"
        :toolbarbutton-name="$t('customer.corpus.addCorpus')"
        @add="openDrawerHandle('add', $event)"
        @delete="DeleteHandle($event)"
        @edit="openDrawerHandle('edit', $event)"
      />
    </Page>
    <!-- 弹窗框 -->
    <Drawer class="w-[35%]" destroy-on-close="true" @refresh="reloadTable" />
  </div>
</template>

<script setup lang="tsx">
import type { DepartmentQueryType } from './type';

import type { Corpus } from '#/api/agent/model/corpus';

import { Page, useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { deleteCorpus, getCorpusList } from '#/api/agent/corpus';
import { type DepartmentInfo } from '#/api/sys/model/departmentModel';

import ExtraDrawer from './components/drawer.vue';
import { tableColumns } from './schemas';
// 弹窗连接
const [Drawer, drawerApi] = useVbenDrawer({
  // 连接抽离的组件
  connectedComponent: ExtraDrawer,
});
const FosoTableRef = useTemplateRef('DepartmentTable');

// 表单数据
const formData = ref<DepartmentQueryType>({});

// 获取表格数据
const getDepListData = async (params: any) => {
  const { page = 1, pageSize = 5 } = params;
  const res = await getCorpusList({ page, pageSize, ...formData.value }); // 调用实际的 API 获取数据

  return {
    total: res.total,
    items: res.data,
  };
};

/**
 * @author Buke
 * @description 打开弹窗
 * @param {string} type - 操作类型，'edit' 表示编辑，'add' 表示新增。
 * @param {any} row - 要编辑的行数据对象，包含语料相关信息。
 * @returns {void}
 */
const openDrawerHandle = (type: string, row?: DepartmentInfo): void => {
  if (type === 'edit') {
    drawerApi.setState({ title: $t('customer.corpus.editCorpus') });
    drawerApi.setData({ type: 'editData', id: row?.id });
    drawerApi.open(); // 注意弹框打开需要分开，不能用同一个
  }
  if (type === 'add') {
    drawerApi.setState({ title: $t('customer.corpus.addCorpus') });
    drawerApi.setData({ type: 'addData' });
    drawerApi.open(); // 注意弹框打开需要分开，不能用同一个
  }
};

/**
 * @author Buke
 * @description 删除语料
 * @param {any} row - 要删除的行数据。
 * @returns {void}
 */
async function DeleteHandle(row: Corpus): Promise<void> {
  await deleteCorpus(row.id as any);
  ElMessage.success($t('common.operateSuccess'));
  FosoTableRef.value?.gridApi.reload();
}

/**
 * @author Buke
 * @description 处理表格数据加载完成后的操作，如更新表格数据。
 * @returns {void}
 */
const reloadTable = (): void => {
  FosoTableRef.value?.gridApi.reload();
  drawerApi.close();
};
</script>
